// utils/uploadHelper.js
import http from '@/http/index.js'
import { api } from '@/api/index.js'
import { ElMessage } from 'element-plus'

export function createUploader({
    onlyGetInputFiles = false,
    uploadApi = api.uploadFile,
    inputAccept = '*/*',
    multiple = false,
    onGetInputFiles = (files) => { },
    onUploadResult = (res, files) => { },
}) {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = inputAccept
    input.multiple = multiple

    // 核心：不要在这里直接触发 input.click()！
    input.onchange = (e) => handleFiles(e.target.files)

    function handleFiles(files) {
        if (!files || files.length === 0) {
            ElMessage.error('未选择文件')
            return
        }

        if (onlyGetInputFiles) {
            onGetInputFiles(files)
        } else {
            const formData = new FormData()
            Array.from(files).forEach(file => formData.append('file', file))

            http.post(uploadApi, formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            }).then(res => {
                onUploadResult(res, files)
                if (res.code === 200) {
                    ElMessage.success(res.msg)
                } else {
                    ElMessage.error(res.msg || '上传失败')
                }
            }).catch(err => {
                console.error('上传失败:', err)
                ElMessage.error('上传失败')
            })
        }
    }

    return {
        triggerSelectFile() {
            input.click() // 只有主动调用时才弹出选择框
        },
        bindDragDropArea(el) {
            if (!el) return
            el.addEventListener('dragover', e => {
                e.preventDefault()
                el.classList.add('drag-over')
            })
            el.addEventListener('dragleave', () => {
                el.classList.remove('drag-over')
            })
            el.addEventListener('drop', e => {
                e.preventDefault()
                el.classList.remove('drag-over')
                const files = e.dataTransfer.files
                handleFiles(files)
            })
        }
    }
}
